﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：ResultWrapperHandler.cs
// 功能描述：TongTongMall.WebApi
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TongTongMall.Dependecy;
using TongTongMall.WebApi.Models;
using TongTongMall.WebApi.WebApi.Configuration;

namespace TongTongMall.WebApi.WebApi.Controllers
{
    /// <summary>
    /// 包装webapi返回的结果
    /// </summary>
    public class ResultWrapperHandler : DelegatingHandler, ITransientDependency
    {
        private readonly IWebApiModuleConfiguration _webApiModuleConfiguration;

        public ResultWrapperHandler(IWebApiModuleConfiguration webApiModuleConfiguration)
        {
            _webApiModuleConfiguration = webApiModuleConfiguration;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken).ContinueWith(
                task =>
                {
                    WrapResultIfNeeded(request, task.Result);
                    return task.Result;

                }, cancellationToken);

            if (cancellationToken.IsCancellationRequested)
            {
                return new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }
            return response;
        }

        /// <summary>
        /// 包装需要包装的ajax结果
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        protected virtual void WrapResultIfNeeded(HttpRequestMessage request, HttpResponseMessage response)
        {
            if (!response.IsSuccessStatusCode)
            {
                return;
            }

            var wrapAttr = HttpActionDescriptorHelper.GetWrapResultAttributeOrNull(request.GetActionDescriptor())
                           ?? new WrapResultAttribute(false, false);
            //是否包装成功的数据
            if (!wrapAttr.WrapOnSuccess)
            {
                return;
            }

            object resultObject;
            if (!response.TryGetContentValue(out resultObject) || resultObject == null)
            {
                response.StatusCode = HttpStatusCode.OK;
                response.Content = new ObjectContent<AjaxResponse>(
                    new AjaxResponse(),
                    _webApiModuleConfiguration.HttpConfiguration.Formatters.JsonFormatter
                    );
                return;
            }

            if (resultObject is AjaxResponse)
            {
                return;
            }

            response.Content = new ObjectContent<AjaxResponse>(
                new AjaxResponse(resultObject),
                _webApiModuleConfiguration.HttpConfiguration.Formatters.JsonFormatter
                );
        }
    }
}
